/**
 * jQuery for module textbooks - controller department
 * 
 * @author	huytbt
 * @date	2012-05-04
 * @version	1.0
 */

;if(window.jQuery) (function($){
	if (!jQuery.h) jQuery.extend({h:{}}); // declare alias $.h
	if (!jQuery.h.textbooks) jQuery.h.textbooks = {}; // declare alias $.h.textbooks
	jQuery.h.textbooks.department = {
		/**
		 * Class FormAddDepartment - used to process add department
		 */
		FormAddDepartment: function(element)
		{
			var _this = this;
			_this.instance = $(element);
			
			_this.initForm = function(){
				_this.instance.submit(function(){
					_this.instance.find(':submit').attr("disabled", "true");
					_this.instance.find('.errorMessage').fadeOut();
					$.ajax({
						dataType: 'JSON',
						type: _this.instance.attr('method'),
						data: _this.instance.serialize(),
						url: _this.instance.attr('action'),
						success: function(response) {
							_this.instance.find(':submit').removeAttr("disabled");
							if (response.error) {
								$.each(response.data, function(key, value){
									var html = value.join('<br/>');
									_this.instance.find('.errorMessage.errorField_'+key).html(html).fadeIn();
								});
							} else
								window.location = window.location;
						}
					});
					
					return false;
				});
				
				return _this;
			};
		},
		/**
		 * Class FormSearchDepartment - used to process search department
		 */
		FormSearchDepartment: function(element)
		{
			var _this = this;
			_this.instance = $(element);
			
			_this.initForm = function(){
				_this.instance.submit(function(){
					var text = _this.instance.find('#input_name').val();
					var search = $('a[title="'+text+'"]');
					if (search.length) {
						window.location = search.attr('href');
					} else {
						_this.instance.find('.errorMessage.errorField_name').html('This department doesn\'t exists in this university').fadeIn();
					}
					
					return false;
				});
				
				return _this;
			};
		}
	};
})(jQuery);

;if(window.jQuery) (function($){
	$(document).ready(function(){
		$('form.h-textbooks-form-add-department').each(function(){
			var $addDepartment = new jQuery.h.textbooks.department.FormAddDepartment(this);
			$addDepartment.initForm();
		});
		
		$('form.h-textbooks-form-search-department').each(function(){
			var $searchDepartment = new jQuery.h.textbooks.department.FormSearchDepartment(this);
			$searchDepartment.initForm();
		});
	});
})(jQuery);